﻿using NetMQ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NETMQLib
{
    public class ReqMQ
    {
        NetMQ.Sockets.RequestSocket requestSocket = null;
        int timeout = 2000;
        string url = "";
        public BaseMQModel BaseMQInfo { get; set; }
        object sendObj = new object();

        public ReqMQ(string ip, int port, int timeout = 2000)
        {
            BaseMQInfo = new BaseMQModel() { IP = ip, Port = port };
            this.timeout = timeout;
            url = $"inproc://{ip}:{port}";
            requestSocket = new NetMQ.Sockets.RequestSocket();
            requestSocket.Connect(url);
        }
        

        public string SendData(string msg)
        {
            try
            {
                lock (sendObj)
                {

                    //如果释放了就重新new
                    if (requestSocket.IsDisposed)
                    {
                        requestSocket = new NetMQ.Sockets.RequestSocket();
                        requestSocket.Connect(url);
                    }
                    requestSocket.SendFrame(msg);
                    //超过固定时间则结束接收
                    bool pollResult = requestSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(timeout), out string backMsg);
                    if (!pollResult)//超时接收或者rep端关闭了，则释放连接
                    {
                        backMsg = "timeout";
                        requestSocket.Disconnect(url);
                        requestSocket.Dispose();
                    }
                    return backMsg;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Dispose()
        {
            if (requestSocket!=null&&!requestSocket.IsDisposed)
            {
                requestSocket.Dispose();
                requestSocket.Close();
            }
        }
    }

    public enum TransportProtocalEnum
    {
        tcp,
        inpoc,
        ipc,
        pgm
    }
}
